package com.ridbor001.demo.servlet;

import com.ridbor001.demo.bean.RDBStudent;
import com.ridbor001.demo.bean.RDBStudentCourse;
import com.ridbor001.demo.bean.RDBUser;
import com.ridbor001.demo.service.RDBGradeService;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/gradeManage")
public class RDBGradeManageServlet extends HttpServlet {
    RDBGradeService gradeService = new RDBGradeService();
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        RDBUser user = (RDBUser) session.getAttribute("user");
        if (user == null) {
            resp.sendRedirect("rDBLogin.jsp");
        } else if (user.isTeacher()) {
            String searchKey = req.getParameter("searchKey");
            List<RDBStudentCourse> data = null;
            try {
                data = searchKey == null ?
                        gradeService.getAllRelations() :
                        gradeService.search(searchKey);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }


            req.setAttribute("relations", data);
            req.getRequestDispatcher("/rDBGradeManage.jsp").forward(req, resp);
        }
        else {
            RDBStudent student = (RDBStudent) session.getAttribute("user");
            String studentId = student.getStudentId();
            List<RDBStudentCourse> data = null;
            try {
                data = gradeService.getRelationsById(studentId);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            req.setAttribute("relations",data);
            req.getRequestDispatcher("/rDBGradeManage.jsp").forward(req,resp);
        }
    }
}